import java.io.*;
import java.net.*;
import java.util.*;
import java.security.Security;
import java.security.Provider;
import javax.net.ssl.*;
import local.util.MyPrint;

/********************************************************************************
 * public void setUrl (String symbol)
 * public void loadData ()
   * private connectToUrl(myUrl)
   * private putInVectorByLine (input)
   * private selectUsefulInfo (vInput)
 * public String getTodaysDataString()
 * public Hashtable getTodaysDataHashTable(String symb)
 * public Vector getTodaysDataVector( )
 ********************************************************************************/

public class GetTodaysData {    

    private String myUrl        = null;
    private String startString  = null;
    private String stopString   = null;
    private String sInput = new String();
    private Vector vInput = new Vector(10);

    private static Hashtable dataHashTable = new Hashtable();
    private static Hashtable tickHashTable = new Hashtable();

    public static void main (String args[]) {

	if (args.length < 2) {
	    System.out.println("=================");
	    System.out.println("\t[1][TICK]");
	    System.out.println("\t[2][TICK FILE]");
	    System.out.println("=================");
	    System.exit(1);
	}

	String choice = args[0];
	String tick   = null;

	if (choice.equals("1")) {
	   
	    String lastVolume = "0";
	    String thisVolume = "0";
	    int    change1 = 0;
	    int    change2 = 0;

	    tick = args[1];

	    GetTodaysData myData = new GetTodaysData();
	    myData.setUrl("https://www.bigcharts.com/custom/datek-com/datek-rt2.asp?osymb=&symb="+tick+
			  "&time=1dy&freq=1mi&compidx=aaaaa%7E0&comp=&type=2&ma=0&maval=9&uf=0&lf=1&"+
			  "lf2=0&lf3=0&sid=&x=42&y=6");
	    myData.setStartString("<td align=center><font face=\"Arial,Helvetica,Geneva\" size=\"1\">52 Week Range</font></td>");
	    myData.setStopString("<table width=97% cellpadding=0 cellspacing=0 border=0 align=center>");
	    myData.loadData();
	    dataHashTable = myData.getTodaysDataHashTable(tick);
	    printHead();
	    //thisVolume = ((String)dataHashTable.get("Volume")).replaceAll(",","");
	    //change1 = Integer.parseInt(thisVolume);
	    //change2 = Integer.parseInt(lastVolume);
	    //System.out.print(Integer.toString(change1-change2)+"\t");
	    myData.printData(dataHashTable);
	    //lastVolume = ((String)dataHashTable.get("Volume")).replaceAll(",","");
	}
	else if (choice.equals("2")) {

	    String file_name = args[1];

	    if ((new File(file_name)).isFile()) {
		MyPrint.message ("Getting Tick from file......");

		GetTickFromFile getTick = new GetTickFromFile ();
		getTick.setTickFileName(file_name);
		getTick.loaderTickFile();
		tickHashTable = getTick.getTickHashTable();

		printHead();

		Enumeration enum = tickHashTable.keys();
		while (enum.hasMoreElements()) {

		    tick = (String)enum.nextElement();

		    GetTodaysData myData = new GetTodaysData();
		    myData.setUrl(tick);
		    myData.loadData();
		    dataHashTable = myData.getTodaysDataHashTable(tick);
		    myData.printData(dataHashTable);
		}
	    }
	}
    }

    public void printData(Hashtable dataTable) {
	String temp; int i = 0;
	String temp2="";
	Calendar c = Calendar.getInstance();
	
	if ( c.get(Calendar.AM_PM)==1) {
	    System.out.print((c.get(Calendar.HOUR)+12));
	}
	else {
	    System.out.print(c.get(Calendar.HOUR));
	}
	if(c.get(Calendar.MINUTE)<10) {
	    System.out.print(":0"+c.get(Calendar.MINUTE)+"\t");
	}
	else {
	    System.out.print(":"+c.get(Calendar.MINUTE)+"\t");
	}
	//System.out.print(c.get(Calendar.SECOND)+"\t");
	System.out.print(dataTable.get("SYMBOL")+"\t");  
	System.out.print(dataTable.get("Last")+"\t");  
	System.out.print(dataTable.get("Change")+"\t");  
	System.out.print(dataTable.get("HIGH")+"\t");  
	System.out.print(dataTable.get("LOW")+"\t");
	temp = (String)dataTable.get("Volume");
	temp = temp.replaceAll(",","");
	i = 10 - temp.length();

	if (i>0) {
	    for (int m=0; m<i; m++) {
		temp2 = temp2 +" ";
	    }
	}

	System.out.print(temp2+temp+"\t\t");
	System.out.println(dataTable.get("Prev. Close")+"\t");
    } 

    public void setUrl (String url) {
	myUrl = url ;
    }

    public void setStartString (String start_string) {
	startString = start_string ;
    }

    public void setStopString (String stop_string) {
	stopString = stop_string ;
    }

    public void loadData () {
	connectToUrl(myUrl);
	vInput = putInVectorByLine (sInput);
	vInput = selectUsefulInfo (vInput);
    }

    public String getTodaysDataString( ) {
	StringBuffer tempBf = new StringBuffer ();
	String temp = null;
	Enumeration penum = vInput.elements();
	while ( penum.hasMoreElements()) {
	    temp = (String)penum.nextElement();
	    if (temp != null) {
		tempBf.append(temp+"\t");
	    }
	}
	return (tempBf.toString()); 
    }

    public Vector getTodaysDataVector( ) {
 
	return vInput; 
    }

    public Hashtable getTodaysDataHashTable(String symb ) {
	Hashtable dTable = new Hashtable();
	String key[]    = {"SYMBOL","","","","","","","","","",""};
	String valume[] = {symb,"","","","","","","","","",""};
	int i = 1; int m = 1;

	Enumeration penum = vInput.elements();
	while ( penum.hasMoreElements()) {
	    if(i<11) {
		key[i] = (String)penum.nextElement();
		i++;
	    }
	    else {
		valume[m] = (String)penum.nextElement();
		m++;
	    }  
	    for (int n=0; n<key.length; n++) {
		dTable.put( (Object)(key[n]), (Object)valume[n]);
	    }
	}
	return dTable; 
    }

    private void connectToUrl (String urlAddress) {
        URL url = null;        
	HttpsURLConnection httpsConnection = null;
	String up;

	try {            
	    url = new URL (urlAddress);  
	    try {
		System.out.println("Connecting to URL \n: "+urlAddress);
		httpsConnection = (HttpsURLConnection)url.openConnection();                
		httpsConnection.setDoOutput(false);                
		httpsConnection.connect();                
		
		System.out.println("Connection Code and Message:" + 
				   httpsConnection.getResponseCode() + 
				   " - " + httpsConnection.getResponseMessage()+"\n");
		
		BufferedReader in = new BufferedReader(new InputStreamReader
		    (httpsConnection.getInputStream()));

		StringBuffer buff1= new StringBuffer("");
		sInput = in.readLine();
		/*
		while (!(sInput.trim()).startsWith(startString)) {
		    sInput = in.readLine();
		    continue;
		}
		*/
		while (sInput != null) {
		    //System.out.println("$$"+sInput);
		    buff1.append(sInput);
		    sInput = in.readLine();
		    /*
		    if (sInput.startsWith(stopString)) {
			break;
		    }
		    */
		}

		in.close();            

		sInput =  buff1.toString();
		sInput = sInput.replaceAll("\n","");
		sInput = sInput.replaceAll("\t","");
		sInput = sInput.replaceAll("&nbsp;","");
		sInput = sInput.replaceAll(">",">\n");
		sInput = sInput.replaceAll("</","\n</");

		//System.out.println(sInput);

	    } catch (IOException ioe) {                
		System.out.println(ioe.getMessage());  
		System.exit(1);            
	    }        
	} catch (MalformedURLException mue) {            
	     System.out.println(mue.getMessage());            
	    System.exit(1);        
	} catch (Exception e) {            
	    e.printStackTrace();            
	    System.exit(1);        
	}    
    }

    private Vector putInVectorByLine (String sinput) {

	Vector v = new Vector (10);
	String element = "";
	StringTokenizer tokens = new StringTokenizer(sinput, "\n");
	while (tokens.hasMoreTokens()) {
	    element = tokens.nextToken();
	    if (element != null) {
		v.addElement(element);
	    }
	}
	
	return v;
    }

    private Vector selectUsefulInfo (Vector v_in) {
	Vector v_out = new Vector (10);
	String text = "";
	Enumeration penum = v_in.elements();
	
	while ( penum.hasMoreElements()) {

	    text = (String)penum.nextElement();
	    if (text.startsWith("<font face=\"Arial,Helvetica,Geneva\" size=\"1\">")) {
		break;
	    }
	}
	
	while ( penum.hasMoreElements() ) {
	    text = (String)penum.nextElement();
	    if (text.startsWith("HELP")) {
		break;
	    }
	    if (!(text.startsWith("<") || text.startsWith("+") || text.startsWith("to<"))) {
		//System.out.println("@"+text);
	        if (text.equals("Day's Range")) {
		    v_out.addElement("LOW");
		    v_out.addElement("HIGH");
		}
		else if (text.startsWith("52")) {
		    v_out.addElement("52LOW");
		    v_out.addElement("52HIGH");
		}
		else {
		    System.out.println(text);
		    v_out.addElement(text);
		}
	    }
	}
	
	return v_out;
    }

    public static void printHead () {

      System.out.print("TIME\t");
      System.out.print("SYMBOL\t");
      System.out.print("LAST\t");
      System.out.print("CHANGE\t");
      System.out.print("HIGH\t");
      System.out.print("LOW\t");
      System.out.print("    VOLUME\t\t");
      System.out.print("PRE_CLOSE\t");
      System.out.print("HIGH\t");
      System.out.print("LOW\t");
      System.out.print("52HIGH\t");
      System.out.println("52LOW\t");

    }

    private void printVector( Vector inputV) {

	int m =0;
	Enumeration penum = inputV.elements();
	while ( penum.hasMoreElements()) { 
	   System.out.print(penum.nextElement()+"\t");
	   m++;
	   if (m==10) {
	       System.out.println();
	   }
	}
    }
}






